import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex) // vue的插件机制

let _userInfo = uni.getStorageSync('userInfo') || null;
let _token = uni.getStorageSync('token') || '';
let _sid = uni.getStorageSync('sid') || null;
let _ascriptionUserId = uni.getStorageSync('ascriptionUserId') || null;
let _indexForm = uni.getStorageSync('indexForm') || {};

// Vuex.Store 构造器选项
const store = new Vuex.Store({
	// 为了不和页面或组件的data中的造成混淆，state中的变量前面建议加上$符号
	state: {
		$userInfo: _userInfo,// 用户信息
		$token: _token,
		$sid:_sid,
		$ascriptionUserId:_ascriptionUserId,
		$indexForm:_indexForm
	},
	mutations: {
		set_sid(state, data){
			state.$sid = data;
			uni.setStorageSync('sid', data);
		},
		set_ascriptionUserId(state, data){
			state.$ascriptionUserId = data;
			uni.setStorageSync('ascriptionUserId', data);
		},
		set_userInfo(state, data) {
			state.$userInfo = data;
			uni.setStorageSync('userInfo', data)
		},
		set_token(state, data) {
			state.$token = data;
			uni.setStorageSync('token', data)
		},
		update_index_form(state, data){
			let $indexForm = state.$indexForm;
			$indexForm[data.key] = data.value;
			uni.setStorageSync('indexForm', $indexForm)
		},
		clear_index_form(state, data){
			state.$indexForm = {};
			uni.removeStorageSync('indexForm');
		}
	},
	getters: {
		get_indexForm(state){
			let $indexForm = state.$indexForm;
			return $indexForm
		},
		get_sid(state){
			let sid = state.$sid;
			return sid
		},
		get_ascriptionUserId(state){
			let ascriptionUserId = state.$ascriptionUserId;
			return ascriptionUserId
		},
		get_userInfo(state) {
			let userInfo = state.$userInfo;
			return userInfo
		},
		get_token(state) {
			let token = state.$token;
			return token
		},
		get_isLogin(state) {
			let token = state.$token;
			let userInfo = state.$userInfo || null;
			return !!(token && userInfo)
		},
	},
	actions: {
		modal(state, content) {
			let params = {
				title: '提示',
				content: '',
				confirmColor: '#2623D1',
				showCancel: true,
				cancelText:'cancel',
				confirmText:'confirm',
			};
			if (typeof content == 'string') {
				params.content = content;
			}
			if (typeof content == 'object') {
				Object.assign(params, content);
			}

			return new Promise((resolve, reject) => {
				uni.showModal({
					...params,
					success: function(res) {
						if (res.confirm) {
							resolve();
						} else if (res.cancel) {
							reject()
						}
					}
				});
			})
		},
		logout(state) {
			this.commit('set_userInfo', null);
			this.commit('set_token', null);
			// this.commit('set_role', null);
		}
	}
})

export default store